#include "Db_manager.h"

vector<string> Db_manager::dbnames;

bool Db_manager::exists(const vector<string> &v, const string &s)
{
	return find(v.begin(), v.end(), s) != v.end();
}

void Db_manager::list()
{
	vector<string> ret;

	WIN32_FIND_DATA f;
	HANDLE h = FindFirstFile("./*.dat", &f);
	if(h != INVALID_HANDLE_VALUE)
	{
		string pref = "";
		bool good = false;

		do
		{
			pref = get_prefix(f.cFileName);
			if(pref != "")
			{
				good = true;

				if(ret.size() > 0)
				{
					good = ret.back() != pref;
				}

				if(good)
				{
					ret.push_back(pref);
				}
			}
		} while(FindNextFile(h, &f));
	}
	else
	{
		//fprintf(stderr, "Error opening directory\n");
	}
	
	dbnames = ret;
}

string Db_manager::load(const bool &newdb)
{
	string name = "";
	if(newdb)
	{
		bool err = false;
		do
		{
			if(err)
			{
				cout << "Db is already exists. Type another name." << endl;
			}
			name = Validator::get<string>("Type the new db's name: ", "Not a valid db name. Try again.");
			err = Db_manager::exists(dbnames, name);
		} while(err);
	}
	else
	{
		vector<string> l = get_dbnames();
		int sel = 0;
		int lsize = static_cast<int>(l.size());

		cout << "Choose a db from the list" << endl;
		do
		{
			int i = 0;
			for(i=0; i<lsize; ++i)
			{
				cout << (i+1) << ". " << l[i] << endl;
			}
			cout << i+1 << ". back" << endl;
			sel = Validator::get<int>("Select an option: ");
		} while(sel <= 0 || sel > lsize+1);

		if(sel < lsize+1)
		{
			name = l[sel-1];
		}
	}
	return name;
}

string Db_manager::get_prefix(const string &a)
{
	int apos = a.find('_');
	if(apos!=string::npos)
	{
		return a.substr(0, apos);
	}
	return "";
}


vector<string> Db_manager::get_dbnames()
{
	return dbnames;
}